package cc.linker.steplink.crm.merchant.service.impl;

import cc.linker.steplink.crm.commons.BeanMapUtils;
import cc.linker.steplink.crm.commons.utils.NumberUtils;
import cc.linker.steplink.crm.merchant.dao.NewMallDao;
import cc.linker.steplink.crm.merchant.dao.ShopGoodsMapper;
import cc.linker.steplink.crm.merchant.dao.mall.MallsMapper;
import cc.linker.steplink.crm.merchant.service.mall.MallsService;
import cc.linker.steplink.crm.merchanth5.dao.MaiBaoLaDao;
import cc.linker.steplink.crm.merchanth5.service.MallService;
import cc.linker.steplink.crm.response.GlobalException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class MallsServiceImpl implements MallsService {

    @Autowired
    private MallsMapper mallsMapper;
    @Autowired
    private ShopGoodsMapper shopGoodsMapper;
    @Autowired
    private NewMallDao newMallDao;
    @Autowired
    private MaiBaoLaDao maiBaoLaDao;
    @Autowired
    private MallService mallService;

    @Override
    public Map<String, Object> getMallInfo(Map<String, Object> param) {
        return mallsMapper.getMallInfo(param);
    }

    @Override
    public void openMall(Map<String, Object> param) {
        // 判断是否完成商家认证
        String checkStatus = mallsMapper.getCheckStatus(param);
        if (StringUtils.isEmpty(checkStatus) || !"2".equals(checkStatus)) {
            throw GlobalException.build("请先完成商家认证");
        }
        // 判断是否已开通
        Map<String, Object> mallInfo = mallsMapper.getMallInfo(param);
        if (!StringUtils.isEmpty(mallInfo)) {
            throw GlobalException.build("供货商城已开通");
        }
        // 开通
        mallsMapper.openMall(param);
    }

    @Override
    public void saveMallInfo(Map<String, Object> param) {
        // 判断是否已开通
        Map<String, Object> mallInfo = mallsMapper.getMallInfo(param);
        if (StringUtils.isEmpty(mallInfo)) {
            throw GlobalException.build("供货商城未开通");
        }
        // 开通
        mallsMapper.saveMallInfo(param);
    }

    @Override
    public List<Map<String, Object>> goodsList(Map<String, Object> param) {
        List<Map<String, Object>> list = mallsMapper.goodsList(param);
        list.forEach(x -> {
            String mallsAmount = "";
            String mallsAmountMax = "";
            String mallsAmountMin = "";
            if (null != x.get("mallsAmount")) {
                mallsAmount = NumberUtils.fenToYuan((Long) x.get("mallsAmount"));
            }
            if (null != x.get("mallsAmountMax")) {
                mallsAmountMax = NumberUtils.fenToYuan((Long) x.get("mallsAmountMax"));
            }
            if (null != x.get("mallsAmountMin")) {
                mallsAmountMin = NumberUtils.fenToYuan((Long) x.get("mallsAmountMin"));
            }
            x.put("mallsAmount", mallsAmount);
            x.put("mallsAmountMax", mallsAmountMax);
            x.put("mallsAmountMin", mallsAmountMin);
        });
        return list;
    }

    @Override
    public void delete(Long[] goodsIds) {
        // 移除供货商品
        shopGoodsMapper.delete(goodsIds);
        // 销售商处理 失效提示 供货商下架商品，建议删除商品
        String mallsInvalid = "供货商下架商品，建议删除商品";
        Integer mallsInvalidType = 1;
        mallsMapper.changeGoodsStatusByMallsGoodsId(goodsIds, mallsInvalid, mallsInvalidType);
    }

    @Override
    public void changeStatus(Long[] goodsIds, Integer goodsStatus) {
        mallsMapper.changeStatus(goodsIds, goodsStatus);
        // 如果是下架
        if (goodsStatus == 2) {
            String mallsInvalid = "供货商下架商品，建议删除商品";
            Integer mallsInvalidType = 2;
            mallsMapper.changeGoodsStatusByMallsGoodsId(goodsIds, mallsInvalid, mallsInvalidType);
        }
        // 供货商上架
        if (goodsStatus == 1) {
            // 判断失效原因 如果是下架导致失效 销售商商品改为下架
            mallsMapper.changeGoodsStatusDownByMallsGoodsId(goodsIds);
            // 多原因失效，删除下架导致的失效描述
            mallsMapper.changeGoodsStatusMarksByMallsGoodsId(goodsIds);
        }
    }

    @Override
    public void checkRewetting(Long[] goodsIds, String orgId) {
        //  获取当前机构的支付抽成 已乘100
        //  Double linkTake = mallsMapper.getLinkTakeByOrgId(orgId);
        //  现在按照最大的10%来算
        Double linkTake = 0.1;
        List<Map<String, Object>> goodsList = mallsMapper.getGoodsAmountList(goodsIds);

        for (Map<String, Object> goods : goodsList) {
            Double salerAmount = Double.parseDouble(goods.get("salerAmount").toString());
            Double mallsAmount = Double.parseDouble(goods.get("mallsAmount").toString());
            Double goodsFreight = Double.parseDouble(goods.get("goodsFreight").toString());
            Double left = linkTake * (salerAmount + goodsFreight);
            Double right = (mallsAmount + goodsFreight);
            if (left.compareTo(right) > 0) {
                LOGGER.error("调整后可能会有商品出现亏损，goodsId:" + goods);
                throw GlobalException.build("调整后可能会有商品出现亏损，请调整。");
                //  throw GlobalException.build("此商品会出现亏损，是否继续？");
            }
        }

    }

    @Override
    public void addMallsGoods(Map<String, Object> param) {
        // 商品ID
        Long goodsId = Long.valueOf(param.get("goodsId").toString());
        String customerId = param.get("customerId").toString();
        String orgId = param.get("orgId").toString();
        // 1大麦 2联盟商家
        String type = param.get("type").toString();
        // 获取商品详情
        Map<String, Object> params = mallsMapper.getGoodsById(goodsId);
        params.put("orgId", orgId);
        params.put("goodsStatus", 0);
        params.put("malls", 1);
        params.put("classificationId", 0);

        // 获取商品sku
        List<Map<String, Object>> sku = mallsMapper.getSkuById(goodsId);
        // 获取商品spec
        List<Map<String, Object>> goodsSpec = mallsMapper.getSpecById(goodsId);
        // 导入供货商品
        if ("1".equals(type)) {
            // 大麦
            newMallDao.insertGoods(params);
        } else {
            // 联盟商家
            params.put("customerId", customerId);
            maiBaoLaDao.insertGoods(params);
        }
        Long newGoodsId = Long.valueOf(params.get("goodsId").toString());
        // 导入供货商品spec
        if (goodsSpec != null && !goodsSpec.isEmpty()) {
            for (Object o : goodsSpec) {
                if (o instanceof Map) {
                    Map<String, Object> map = (Map) o;
                    map.put("goodsId", newGoodsId);
                    map.remove("id");
                    newMallDao.insertGoodsSpec(map);
                }
            }
        }
        // 导入供货商品sku
        Long totalCount = 0L;
        if (sku != null && !sku.isEmpty()) {
            for (Object o : sku) {
                if (o instanceof Map) {
                    Map<String, Object> map = (Map) o;
                    map.put("goodsId", newGoodsId);
                    Long skuCount = Long.valueOf(map.get("goodsCount").toString());
                    totalCount += skuCount;
                    map.remove("skuId");
                    newMallDao.insertSku(map);
                    mallService.flushGoodsCache(false, newGoodsId, String.valueOf(map.get("newSkuId")), skuCount);
                }
            }
            params.put("goodsCount", totalCount);
            shopGoodsMapper.updateGoods(params);
        }
        mallService.flushGoodsCache(false, newGoodsId, null, totalCount);
    }

    @Override
    public List<Map<String, Object>> getGoodsListStatus(Long[] goodsIds) {
        return mallsMapper.getGoodsListStatus(goodsIds);
    }

    @Override
    public PageInfo mallsGoodsList(Map<String, Object> param) {
        String orderBy = "";
        if (!StringUtils.isEmpty(param.get("order"))) {
            int order = Integer.parseInt(param.get("order").toString());
            if (1 == order) {
                orderBy = "UP_TIME";
            } else if (2 == order) {
                orderBy = "MALLS_AMOUNT";
            } else if (3 == order) {
                orderBy = "SALES_NUM";
            }
        }

        // 判断是否供货商搜索
        if (!StringUtils.isEmpty(param.get("id"))) {
            Integer id = Integer.parseInt(param.get("id").toString());
            Map<String, Object> mallInfo = mallsMapper.mallInfoById(id);
            if (StringUtils.isEmpty(mallInfo)) {
                throw GlobalException.build("暂无该供货商信息！");
            }
            String orgId = mallInfo.get("orgId").toString();
            String customerId = mallInfo.get("customerId").toString();
            if (orgId.equals(customerId)) {
                // 大麦 供货商
                param.put("customerId", "1");
            } else {
                // 联盟商家 供货商
                param.put("customerId", customerId);
            }
        }
        // 根据类目id查询所有的最低级类目
        if (!StringUtils.isEmpty(param.get("classificationId"))) {
            Integer classificationId = (Integer) param.get("classificationId");
            String classId = mallsMapper.getClassList(classificationId);
            param.put("classificationId", classId);
        }
        //
        if ("3".equals(param.get("payMode").toString())) {
            String orgIds = mallsMapper.getOrgIds();
            param.put("orgIds", orgIds);
        }
        param.put("order", orderBy);
        int pageIndex = Integer.parseInt(param.get("pageIndex").toString());
        int pageSize = Integer.parseInt(param.get("pageSize").toString());
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(mallsMapper.mallsGoodsList(param));
    }

    @Override
    public Integer getMallIdByGoodsId(Long goodsId) {
        Map<String, Object> ower = mallsMapper.getOrgIdAndCustomerIdByGoodsId(goodsId);
        String orgId = ower.get("orgId").toString();
        String customerId = StringUtils.isEmpty(ower.get("customerId")) ? orgId : ower.get("customerId").toString();
        Map<String, Object> map = new HashMap<>();
        map.put("orgId", orgId);
        map.put("customerId", customerId);
        return mallsMapper.getMallId(map);
    }

    @Override
    public Map<String, Object> mallInfoById(Integer id) {
        Map<String, Object> result = mallsMapper.mallInfoById(id);
        if (StringUtils.isEmpty(result)) {
            throw GlobalException.build("暂无该供货商信息！");
        }
        String orgId = result.get("orgId").toString();
        String customerId = result.get("customerId").toString();
        if (orgId.equals(customerId)) {
            customerId = "";
        }
        // 获取供货商商品数和总销量
        Map<String, Object> goodsCount = mallsMapper.getGoodsCount(orgId, customerId);
        result.putAll(goodsCount);
        Map<String, Object> salerNum = mallsMapper.getSalerNum(orgId, customerId);
        result.putAll(salerNum);
        result.remove("orgId");
        result.remove("customerId");
        return result;
    }

    @Override
    public void addGoodsShop(Map<String, Object> param) {
        int ifSelf = 0;
        int ifExist = 0;
        //8.点击“上架至商城按钮”校验此商品是否由添加者创建若是则提示“无法添加自己的商品”
        ifSelf = mallsMapper.getIfSelfGoods(param);
        if (ifSelf == 1) {
            throw GlobalException.build("无法添加自己的商品");
        }
        //9.当此商品在此销售商“商品管理”中存在，按钮切换为“已上架至商城”并无法点击
        ifExist = mallsMapper.getIfExistGoods(param);
        if (ifExist == 1) {
            throw GlobalException.build("已上架至商城");
        }
        // 商品ID
        Long goodsId = Long.valueOf(param.get("goodsId").toString());
        String customerId = param.get("customerId").toString();
        String orgId = param.get("orgId").toString();
        String groupIds = param.get("groupIds").toString();
        Integer classificationId = (Integer) param.get("classificationId");

        // 1大麦 2联盟商家
        String type = param.get("type").toString();
        // 获取商品详情
        Map<String, Object> params = mallsMapper.getGoodsById(goodsId);
        // 建议零售价最小值
        Double mallsAmountMin = 0.00;
        if (!StringUtils.isEmpty(params.get("mallsAmountMin"))) {
            mallsAmountMin = Double.parseDouble(params.get("mallsAmountMin").toString());
        }
        params.put("orgId", orgId);
        params.put("goodsStatus", 2);
        params.put("malls", 0);
        params.put("classificationId", classificationId);
        params.put("mallsGoodsId", goodsId);
        params.put("moneyAmount", mallsAmountMin);
        params.remove("goodsId");
        // 获取商品sku
        List<Map<String, Object>> sku = mallsMapper.getSkuById(goodsId);
        // 获取商品spec
        List<Map<String, Object>> goodsSpec = mallsMapper.getSpecById(goodsId);
        // 导入供货商品
        if ("1".equals(type)) {
            // 大麦
            newMallDao.insertGoods(params);
        } else {
            // 联盟商家
            params.put("customerId", customerId);
            maiBaoLaDao.insertGoods(params);
        }
        Long newGoodsId = Long.valueOf(params.get("goodsId").toString());

        // 导入商品分组表
        List<String> groupId = Arrays.asList(groupIds.split(","));
        newMallDao.updateRelationByList(newGoodsId, groupId);

        // 导入供货商品spec
        if (goodsSpec != null && !goodsSpec.isEmpty()) {
            for (Map<String, Object> map : goodsSpec) {
                if (map != null) {
                    map.put("goodsId", newGoodsId);
                    map.remove("id");
                    newMallDao.insertGoodsSpec(map);
                }
            }
        }

        // 导入供货商品sku
        Long totalCount = 0L;
        if (sku != null && !sku.isEmpty()) {
            for (Map<String, Object> map : sku) {
                if (map != null) {
                    map.put("goodsId", newGoodsId);
                    map.put("mallsSkuId", map.get("skuId"));
                    map.put("moneyAmount", map.get("mallsAmountMin"));
                    map.put("mallsAmount", Double.parseDouble(map.get("mallsAmount").toString()));
                    Long skuCount = Long.valueOf(map.get("goodsCount").toString());
                    totalCount += skuCount;
                    map.remove("skuId");
                    newMallDao.insertSku(map);
                    long newSkuId = Long.parseLong(map.get("newSkuId").toString());
                    mallService.flushGoodsCache(false, newGoodsId, String.valueOf(newSkuId), skuCount);
                }
            }
            params.put("goodsCount", totalCount);
            shopGoodsMapper.updateGoods(params);
        }
        if (totalCount < 1 && !StringUtils.isEmpty(params.get("goodsCount"))) {
            totalCount = Long.valueOf(params.get("goodsCount").toString());
        }
        mallService.flushGoodsCache(false, newGoodsId, null, totalCount);
    }

    @Override
    public Map<String, Object> getMallsGoodsStatus(Map<String, Object> param) {
        int ifSelf = 0;
        int ifExist = 0;
        //8.点击“上架至商城按钮”校验此商品是否由添加者创建若是则提示“无法添加自己的商品”
        ifSelf = mallsMapper.getIfSelfGoods(param);
        //9.当此商品在此销售商“商品管理”中存在，按钮切换为“已上架至商城”并无法点击
        ifExist = mallsMapper.getIfExistGoods(param);
        Map<String, Object> result = new HashMap<>();
        result.put("ifSelf", ifSelf);
        result.put("ifExist", ifExist);
        return result;
    }

    @Override
    public PageInfo centerMallsList(Map<String, Object> param) {
        int pageIndex = Integer.parseInt(param.get("pageIndex").toString());
        int pageSize = Integer.parseInt(param.get("pageSize").toString());
        PageHelper.startPage(pageIndex, pageSize);
        return new PageInfo<>(mallsMapper.centerMallsList(param));
    }

    @Override
    public List<String> getLinkerOrgList() {
        return mallsMapper.getLinkerOrgList();
    }

    @Override
    public void mallsGoodsChangeHot(String goodsId) {
        mallsMapper.mallsGoodsChangeHot(goodsId);
    }

    @Override
    public void handleTopSort(String goodsId, Integer sort) {
        if (StringUtils.isEmpty(goodsId) || StringUtils.isEmpty(sort)) {
            throw GlobalException.build("参数错误");
        }
        if (sort == 0) {
            // 0取消置顶 置顶字段null  排序字段1
            mallsMapper.handleTopSort(goodsId, 0);
            // 其他排序 商品字段加一
            mallsMapper.handleOtherGoodsNormalSort(goodsId);
        } else {
            // 1置顶 置顶字段1 排序字段null
            mallsMapper.handleTopSort(goodsId, 1);
            // 其他置顶商品 topId 加一
            mallsMapper.handleOtherGoodsTopSort(goodsId);
        }
    }

    @Override
    public void handleNormalSort(String goodsId, Integer sort) {
        String oldGoodsId = "";
        Integer oldSort = null;
        Integer nowSort = null;
        // 获取所有供货商品的列表
        Map<String, Object> param = new HashMap<>();
        List<Map<String, Object>> list = mallsMapper.centerMallsList(param);
        for (int i = 0; i < list.size(); i++) {
            String nowGoodsId = list.get(i).get("goodsId").toString();
            if (goodsId.equals(nowGoodsId)) {
                nowSort = Integer.parseInt(list.get(i).get("mallsGoodsNormalOrder").toString());
                if (sort == 0) {
                    //下移 获取下一个商品的id 和排序字段
                    oldGoodsId = list.get(i + 1).get("goodsId").toString();
                    oldSort = Integer.parseInt(list.get(i + 1).get("mallsGoodsNormalOrder").toString());
                } else {
                    //上移 获取上一个商品的id 和排序字段
                    if (!StringUtils.isEmpty(list.get(i - 1).get("mallsGoodsTopOrder"))) {
                        break;
                    }
                    oldGoodsId = list.get(i - 1).get("goodsId").toString();
                    oldSort = Integer.parseInt(list.get(i - 1).get("mallsGoodsNormalOrder").toString());
                }
                break;
            }
        }
        if (oldSort == null) {
            throw GlobalException.build("无法移动");
        }
        //  获取当前商品的normalSort
        mallsMapper.handleNormalSort(goodsId, oldSort);
        mallsMapper.handleNormalSort(oldGoodsId, nowSort);
    }

    @Override
    public void checkGoodsRewetting(Map<String, Object> params) {
        Object sku = params.get("sku");
        List<Map> newSku = (List<Map>) sku;
        double goodsFreight = 0;
        if (!StringUtils.isEmpty(params.get("minGoodsFreight")) &&
                !StringUtils.isEmpty(params.get("isFreeFreight")) &&
                "0".equals(params.get("isFreeFreight").toString())) {
            goodsFreight = Double.valueOf(params.get("minGoodsFreight").toString()) * 100;
        } else if (!StringUtils.isEmpty(params.get("goodsFreight")) &&
                !StringUtils.isEmpty(params.get("isFreeFreight")) &&
                "0".equals(params.get("isFreeFreight").toString())) {
            goodsFreight = Double.parseDouble(params.get("goodsFreight").toString()) * 100;
            if (!StringUtils.isEmpty(params.get("getFreightTemplateId"))) {
                goodsFreight = Double.valueOf(maiBaoLaDao.getLeastTemplateFee(params.get("getFreightTemplateId").toString())) * 100;
            }
        }
        if (goodsFreight > 0) {
            int goodsFreight2 = new BigDecimal(goodsFreight).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
            goodsFreight = goodsFreight2;
        }
        if (newSku == null || newSku.size() < 1) {
            // 单规格
            // 销售金额
            double amount = Double.parseDouble(params.get("mallsAmountMax").toString()) * 100;
            // 供货价
            double mallsAmount = 0.0;
            if (!StringUtils.isEmpty(params.get("mallsAmount"))) {
                mallsAmount = Double.parseDouble(params.get("mallsAmount").toString()) * 100;
            }
            // 抽成
            Double v1 = 0.1 * (amount + goodsFreight);
            int allFee = new BigDecimal(v1).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
            double cost1 = allFee;
            // 供货价
            double cost2 = mallsAmount + goodsFreight;
            if (cost1 > cost2) {
                LOGGER.error("调整后可能会有商品出现亏损，goodsId:" + params.get("goodsId"));
                throw GlobalException.build("调整后可能会有商品出现亏损，请调整。");
            }
        } else {
            // 多规格
            for (int i = 0; i < newSku.size(); i++) {
                Object o2 = newSku.get(i);
                Map o1 = BeanMapUtils.beanToMap(o2);
                if (o1.containsKey("empty")) {
                    o1 = (Map<String, Object>) o2;
                }
                try {
                    Map<String, Object> o = o1;
                    // 销售金额
                    double amount = 0;
                    if (!StringUtils.isEmpty(o.get("mallsAmountMax"))) {
                        amount = Double.valueOf(o.get("mallsAmountMax").toString()) * 100;
                    }
                    // 供货价
                    double mallsAmount = 0.0;
                    if (!StringUtils.isEmpty(o.get("mallsAmount"))) {
                        mallsAmount = Double.valueOf(o.get("mallsAmount").toString()) * 100;
                    }
                    // 抽成
                    Double v1 = 0.1 * (amount + goodsFreight);
                    int allFee = new BigDecimal(v1).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                    double cost1 = allFee;
                    // 供货价
                    double cost2 = mallsAmount + goodsFreight;
                    if (cost1 > cost2) {
                        LOGGER.error("调整后可能会有商品出现亏损，goodsId:" + params.get("goodsId"));
                        throw GlobalException.build("调整后可能会有商品出现亏损，请调整。");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    LOGGER.error("调整后可能会有商品出现亏损，goodsId:" + params.get("goodsId"));
                    throw GlobalException.build("调整后可能会有商品出现亏损，请调整。");
                }
            }
        }
    }
}
